package com.pratices.cookie;

import com.pratices.cookie.bean.BaseRespVo;
import com.pratices.cookie.bean.Storage;
import com.pratices.cookie.util.ImageSaver;
import com.pratices.cookie.util.JsonUtil;
import com.pratices.cookie.util.Response6;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@MultipartConfig
@WebServlet("/admin/storage/create")
public class Servelet1 extends HttpServlet {


    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");

        // 获取上传的图片
        Part part = req.getPart("file");
        InputStream inputStream = part.getInputStream();
        String submittedFileName = part.getSubmittedFileName();
        File file = new File("D:\\myPratices\\daydayup\\javaee\\src\\main\\resources\\Image\\" , submittedFileName);
        FileOutputStream outputStream = new FileOutputStream(file);

        //开始上传
        byte[] bytes = new byte[1024];
        int len;
        while ((len = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, len);
        }

        //进行关闭
        inputStream.close();
        outputStream.close();

        //处理响应的JSON字符串
        // 等会在处理响应JSON字符串
        String url = "http://" + req.getLocalAddr() + ":" + req.getLocalPort() + "/wx/storage/fetch/" + submittedFileName;
        Storage storage = new Storage(1, submittedFileName, submittedFileName, part.getContentType(), part.getSize(), url, new Date(), new Date());

        BaseRespVo baseRespVo = BaseRespVo.ok(storage);
        String json = JsonUtil.toJson(baseRespVo);
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().println(json);

    }

}
